package com.xy.tool.data.redis.ex;

import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.SetOperations;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

public class SetOperationsEx<V> {

    private final RedisTemplate<String, V> redisTemplate;
    private final SetOperations<String, V> setOps;

    public SetOperationsEx(RedisTemplate<String, V> redisTemplate) {
        Objects.requireNonNull(redisTemplate);
        this.redisTemplate = redisTemplate;
        this.setOps = redisTemplate.opsForSet();
    }

    public final Set<V> scan(String key, String pattern, int scanSize) {
        Objects.requireNonNull(key, "The key is required.");
        if(scanSize < 1) {
            throw new IllegalArgumentException("The scanSize should be than 0.");
        }
        String pattern0 = pattern == null ? "" : pattern;
        Set<V> values = new HashSet<>();
        Cursor<V> cursor = setOps.scan(key,
                new ScanOptions.ScanOptionsBuilder()
                        .match(pattern0.concat("*"))
                        .count(scanSize)
                        .build());
        while (cursor.hasNext()) {
            values.add(cursor.next());
        }
        return values;
    }

}
